import React, {
    Component,
} from 'react';

import {
    StyleSheet,
    Text,
    View,
    Platform,
    FlatList,
    Dimensions,
    TouchableOpacity,
    Image,
    ScrollView,
    StatusBar,
    Linking,
    ActivityIndicator,
    DeviceEventEmitter,
    TextInput,
} from 'react-native';


import HttpUtils from '../../utils/HttpUtils';
import HttpUrls from '../../utils/HttpUrls';
import Constant from '../../utils/Constant';
import AndroidModule from '../../utils/AndroidConnent';
import NoData from '../../utils/NoData'
import Loading from "../../utils/Loading";
import { getImgUrl } from '../../utils/ComFunction';
const isIos = Platform.OS == 'ios';


import OpenIMSDKRN, { OpenIMEmitter, MessageItem } from 'open-im-sdk-rn';
import RNFS from 'react-native-fs';
import moment from 'moment';
import StatusBarSelf from '../../components/StatusBarSelf';

export default class MessageList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            currentPage: 1,
            tabIndex: 0,//0买家消息 1卖家消息
            showFoot: 0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
            messageList: [],
            operationID: Constant.userInfo.username
        }
    }

    componentWillMount() {

       
    }

    componentWillUnmount() {
        
    }


    componentDidMount() {

        this.getUserConversationList();

    }

    openImLogin() {
        
    }

    login() {
        OpenIMSDKRN.login({
            userID: Constant.IMUserId,
            token: Constant.IMToken,
        }, this.state.operationID).then((result) => {
            console.log('login-success', result);
            this.findAllMessageList();
        }).catch(err => {
            console.log('login-error=', err);
        });
    }

    findAllMessageList() {
        OpenIMSDKRN.getAllConversationList(this.state.operationID)
            .then((data) => {
                // 调用成功
                console.log('getAllConversationList', data);
            })
            .catch(({ errCode, errMsg }) => {
                // 调用失败
                console.log('getAllConversationList', errCode, errMsg);
            });
    }

  


    render() {
        return (
            <View style={styles.container}>
                <StatusBarSelf ></StatusBarSelf>


                {this.renderTop()}
                {this.renderMessageList()}

            </View>
        );
    }

    renderTop() {
        return (
            <View style={styles.toplayout}>
                <TouchableOpacity
                    style={styles.fanhuibox}
                    activeOpacity={0.8}
                    onPress={this.finish}>
                    <Image source={{ uri: isIos ? 'icon_item_back' : 'ic_back' }} style={styles.fanhui} />
                </TouchableOpacity>

                <View style={{ height: '100%', flexDirection: 'row' }}>
                    <TouchableOpacity
                        style={styles.topTab}
                        onPress={() => {
                            this.setState({
                                tabIndex: 0,
                                currentPage: 1,
                                messageList:[]
                            }, function () {
                                this.getUserConversationList()
                            })
                        }}>
                        <Text style={this.state.tabIndex == 0 ? styles.topTitleCheckText : styles.topTitleText}>客户咨询</Text>
                    </TouchableOpacity>

                    <TouchableOpacity
                        style={styles.topTab}
                        onPress={() => {
                            this.setState({
                                tabIndex: 1,
                                currentPage: 1,
                                messageList:[]
                            }, function () {
                                this.getUserConversationList()
                            })
                        }}>
                        <Text style={this.state.tabIndex == 1 ? styles.topTitleCheckText : styles.topTitleText}>车商客服</Text>
                    </TouchableOpacity>
                </View>
            </View>
        )
    }

    renderMessageList() {
        return (
            <View style={{ width: '100%', flex: 1 }}>
                <FlatList
                    style={{ flex: 1, height: '100%' }}
                    showsVerticalScrollIndicator={false}
                    keyExtractor={this._keyExtractor}
                    data={this.state.messageList}
                    renderItem={this.renderMessageItem.bind(this)}
                    // ItemSeparatorComponent={this._itemDivide}
                    onEndReachedThreshold={0.1}
                    onEndReached={() => this.reachedEnd()}
                    ListFooterComponent={() => this.renderFooter()}
                    ListEmptyComponent={this.renderEmpty.bind(this)}
                />
            </View>
        )
    }

    renderMessageItem({ item, index }) {
        return (
            <TouchableOpacity
                key={index}
                style={styles.msgItem}
                onPress={() => {
                    this.clearUnreadCount(index)
                    let obj = {
                        typepage: '1027',
                        imGroupId: item.imGroupId + '',
                        carId: item.consultingCarId + '',
                        type: this.state.tabIndex + ''
                    }
                    AndroidModule.commonRnJump(obj)
                }}>

                <Image style={styles.logoIconImg} source={{ uri: this.state.tabIndex == 0 ? getImgUrl(item.buyerMerchantLogo) : getImgUrl(item.sellerMerchantLogo) }}></Image>

                <View style={{ marginLeft: 12, marginRight: 16, height: 54, justifyContent: 'center', flex: 1 }}>
                    <Text style={styles.msgTitleText} numberOfLines={1} ellipsizeMode={'tail'}>{this.state.tabIndex == 0 ? item.buyerUserName+'@'+ item.buyerMerchantName : item.sellerUserName+'@'+ item.sellerMerchantName}</Text>

                    <Text style={styles.msgContentText} numberOfLines={1} ellipsizeMode={'tail'}>{this.getMsgTypeDes(item.imConversationInfo.msgInfo)}</Text>
                    

                </View>

                <View style={{ height: 44,justifyContent: 'space-between',alignItems:'flex-end' }}>
                    <Text style={styles.msgTimeText}>{moment(item.imConversationInfo.msgInfo.LatestMsgRecvTime).format("MM-DD HH:mm")}</Text>
                    {item.imConversationInfo.unreadCount > 0 ?
                            <View style={styles.unReadContain}>
                                <Text style={styles.unReadText}>{item.imConversationInfo.unreadCount}</Text>
                            </View> :
                            null
                        
                        }
                </View>

                <View style={styles.sepLine}/>

            </TouchableOpacity>

        )
    }

    clearUnreadCount(index) {
        
        let temp = []
        this.state.messageList.map((item, i) => {
            if (i == index) {
                item.imConversationInfo.unreadCount = 0
            }
            temp.push(item)
        })
        this.setState(
            {
                messageList: temp
            }
        )
    }

    getMsgTypeDes(msgInfo) {
        if (msgInfo.contentType == 101) {//文本消息
            return msgInfo.senderName + '：' + JSON.parse(msgInfo.content).content
        } else if (msgInfo.contentType == 102) {//图片消息

            return msgInfo.senderName + '：' + '[图片]'
        } else if (msgInfo.contentType == 103) {//语音消息
            return msgInfo.senderName + '：' + '[语音]' + JSON.parse(msgInfo.content).duration + "\""
        } else if (msgInfo.contentType == 104) {//视频消息
            return msgInfo.senderName + '：' + '[视频]'
        }
        else if (msgInfo.contentType == 105) {//文件消息
            return msgInfo.senderName + '：' + '[文件]' + JSON.parse(msgInfo.content).fileName
        }

        else if (msgInfo.contentType == 110) {//自定义消息
            let contentInfo = JSON.parse(msgInfo.content)
            if (contentInfo.data == '1') {//车辆
                return msgInfo.senderName + '：' + '[车辆]'
            } if (contentInfo.data == '2') {//订单
                return msgInfo.senderName + '：' + '[订单]'
            } 
            else {
                return '其他消息'
            }

        }
        else {
            return '其他消息'
        }
    }

    renderEmpty() {
        if (!this.state.isRefresh) {
            return (
                <NoData Desc="暂无数据" style={{ marginTop: gREM(200) }} />
            )
        } else {
            return (
                null
            )
        }
    }

    renderFooter() {
        if (this.state.condition.length == 0) {
            return null;
        }
        if (this.state.showFoot === 1) {
            return <View style={{ height: Constant.bottomHeight }} />;
        } else if (this.state.showFoot == 2) {
            return (
                <View style={{ padding: 10, backgroundColor: '#ffffff', display: 'flex', flexDirection: 'row', alignItems: 'center', justifyContent: 'center' }}>
                    <ActivityIndicator size="small" color="#FFE000" />
                    <Text style={{ marginLeft: 10, fontSize: 20, color: '#333333' }}>加载中...</Text>
                </View>
            )
        } else {
            return null;
        }


    }

    _itemDivide = () => {
        return <View style={{ height: 0.5, backgroundColor: '#e4e4e4' }} />;
    };

    _keyExtractor = (item, index) => index + '';

    reachedEnd() {
        if (this.state.showFoot != 0) {
            return null;
        }
        let pageNo = this.state.currentPage + 1
        this.setState({
            showFoot: 2,
            currentPage: pageNo
        }, function () {
            this.getUserConversationList()
        });
    }


    sendTextMsg() {

    }


    getUserConversationList() {
        let param = {
            pageNo: this.state.currentPage,
            pageSize: 20,
            imUserId: Constant.IMUserId
        }

        if (this.state.tabIndex == 0) {
            param['role'] = 2
        } else {
            param['role'] = 1
        }

        HttpUtils.postRequest(HttpUrls.getUserConversation, param)
            .then((result) => {
                if (result.data && result.data.resultList.length > 0) {

                    this.setState({
                        messageList: this.state.messageList.concat(result.data.resultList)
                    })
                    if (result.data.resultList.length < 20) {
                        this.setState({
                            showFoot: 1
                        });
                    } else {
                        this.setState({
                            showFoot: 0
                        });
                    }
                } else {
                    this.setState({
                        showFoot: 1
                    });
                }

            })
            .catch((error) => {

            });
    }

    finish() {
        AndroidModule.finish();
    }

}

const styles = StyleSheet.create({
    container: {
        width: '100%',
        height: '100%',
        flexDirection: 'column',

        backgroundColor: '#ffffff'
    },

    toplayout: {
        width: '100%',
        height: 44,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
    },
    fanhuibox: {
        position: 'absolute',
        width: 80,
        height: 44,
        left: 0,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'flex-start',
    },
    fanhui: {
        width: 18,
        height: 16,
        marginLeft: 14,
    },

    topTitleCheckText: {
        fontSize: 18,
        color: '#333333',
        fontWeight: 'bold'
    },
    topTitleText: {
        fontSize: 18,
        color: '#999999',
    },
    topTab: {
        height: '100%',
        justifyContent: 'center',
        alignItems: 'center',
        marginStart: 15,
    },

    msgItem: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-between',
        paddingHorizontal: 15,
        height: 80
    },
    logoIconImg: {
        width: 48,
        height: 48,
        borderRadius: 48,
        backgroundColor: '#e4e4e4',
    },
    msgTitleText: {
        fontSize: 16,
        color: '#333333',
    },
    msgContentText: {
        marginTop: 8,
        fontSize: 14,
        color: '#999999',

    },
    msgTimeText: {
        fontSize: 14,
        color: '#999999',
    },
    unReadContain: {
        width: 18,
        height: 18,
        backgroundColor: 'red',
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: 20
    },
    unReadText: {
        fontSize: 10,
        color: '#ffffff'
    },
    sepLine: {
        width: '100%',
        height: 0.5,
        backgroundColor: '#E4E4E4',
        position: 'absolute',
        bottom: 0,
        left: 15
    }
})